const { getList, getDetail, newBlog, updateBlog, deleteBlog } = require('../controller/blog')
const { successModel, errorModel } = require('../model/resModel')

const handleBlogRouter = (req, res) => {
  const method = req.method
  const author = req.query.author || ''
  const keyword = req.query.keyword || ''
  const id = req.query.id

  if (method === 'GET' && req.path === '/api/blog/list') {
    const result = getList(author, keyword)
    return result.then(listData => {
      return new successModel(listData)
    })
  }

  if (method === 'GET' && req.path === '/api/blog/detail') {
    const result = getDetail(id)
    return result.then(detailData => {
      return new successModel(detailData)
    })
  }

  if (method === 'POST' && req.path === '/api/blog/new') {
    req.body.author = 'Jacky'
    const result = newBlog(req.body)
    return result.then(insertResult => {
      return new successModel(insertResult)
    })
  }

  
  if (method === 'POST' && req.path === '/api/blog/update') {
    const result = updateBlog(id, req.body)
    return result.then(updateResult => {
      if (updateResult) {
        return new successModel(updateResult)
      } else {
        return new errorModel('更新失败')
      }
    })
  }

  if (method === 'POST' && req.path === '/api/blog/delete') {
    const author = 'Jacky'
    const result = deleteBlog(id,author)
    return result.then(deleteResult => {
      if (deleteResult) {
        return new successModel(deleteResult)
      } else {
        return new errorModel('删除失败')
      }
    })
  }
}

module.exports = handleBlogRouter